﻿using Demo.PetaPoco.Application.Dtos.Common;
using Demo.PetaPoco.Application.Dtos.User;
using Demo.PetaPoco.Application.Services.Menu;
using Demo.PetaPoco.Application.Services.User;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PmSoft.Core;
using PmSoft.Web.Abstractions;
using PmSoft.Web.Abstractions.Attributes;
using PmSoft.Web.Abstractions.Authorization;
using PmSoft.Web.Abstractions.Captcha;
using System.Threading.Tasks;

namespace Demo.PetaPoco.WebApi.Controllers;

[Route("api/[controller]")]
[ApiController]
public class AuthController(IApplicationContext applicationContext,
	IJwtService jwtService,
	UserAuthenticationService userAuthenticationService,
	MenuService menuService,
	ClickCaptchaService clickCaptcha) : ControllerBase
{
	/// <summary>
	/// 登录 测试 Pull Request 提交代码
	/// </summary>
	/// <param name="dto"></param>
	/// <returns></returns>
	[HttpPost("login")]
	[AllowAnonymous]
	public async Task<ApiResult<object>> MobileLoginAsync(UserMobileLoginIn dto)
	{
		//if (!await clickCaptcha.CheckAsync(dto.CaptchaId, dto.CaptchaInfo))
		//	return ApiResult.Error("验证码错误");
		var clientInfo = applicationContext.ClientInfo;
		var user = await userAuthenticationService.AuthenticateByMobileAsync(dto.UserName, dto.Password);
		var token = await jwtService.GenerateTokenAsync(user);
		return ApiResult.Ok(new
		{
			id = user.UserId,
			userName = user.Name,
			nickName = user.Name,
			token.AccessToken,
			token.RefreshToken
		});
	}

	/// <summary>
	/// 电子邮箱登录
	/// </summary>
	/// <param name="dto"></param>
	/// <returns></returns>
	[HttpPost("checkInByEmail")]
	[AllowAnonymous]
	public async Task<ApiResult<object>> EmailLoginAsync(UserEmailLoginIn dto)
	{
		//if (!await clickCaptcha.CheckAsync(dto.CaptchaId, dto.CaptchaInfo))
		//	return ApiResult.Error("CAPTCHA_ERROR", "验证码错误");

		var user = await userAuthenticationService.AuthenticateByEmailAsync(dto.UserName, dto.Password);
		var token = await jwtService.GenerateTokenAsync(user);
		return ApiResult.Ok(new
		{
			id = user.UserId,
			userName = user.Name,
			nickName = user.Name,
			token = token.AccessToken,
			token.RefreshToken
		});
	}

	/// <summary>
	/// 获取权限代码
	/// </summary>
	/// <returns></returns>
	[HttpGet("codes")]
	[RestrictAccess]
	public async Task<IApiResult> GetCodesAsync()
	{
		var permCodes = await menuService.GetPermCodesAsync();
		return ApiResult.Ok(permCodes);
	}

	/// <summary>
	/// 刷新token
	/// </summary>
	/// <param name="dto"></param>
	/// <returns></returns>
	[HttpPost("refresh")]
	public async Task<IApiResult> RefreshTokenAsync(RefreshTokenIn dto)
	{
		var token = await jwtService.RefreshTokenAsync(dto.AccessToken, dto.RefreshToken);
		return token == null ? ApiResult.Error("刷新token失败")
			: ApiResult.Ok(new { token?.NewAccessToken, token?.NewRefreshToken });
	}


	/// <summary>
	/// 退出登录
	/// </summary>
	/// <returns></returns>
	[HttpPost("logout")]
	public async Task<ApiResult> LogoutAsync()
	{
		var authedUser = applicationContext.CurrentUser;
		if (authedUser == null)
			return ApiResult.Error("未认证");
		await jwtService.InvalidateUserTokensAsync(authedUser);
		return ApiResult.Ok("退出登录成功");
	}
}
